package com.qianji.petmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianji.common.utils.PageUtils;
import com.qianji.common.utils.Query;
import com.qianji.petmall.product.dao.CategoryDao;
import com.qianji.petmall.product.entity.CategoryEntity;
import com.qianji.petmall.product.service.CategoryService;
import com.qianji.petmall.product.vo.CateLog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationServiceImpl categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redisson;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
//        List<CategoryEntity> oList = baseMapper.selectList(null);
//        List<CategoryEntity> collect = oList.stream().filter((x) -> {
//            return x.getParentCid().intValue() == 0;
//        }).collect(Collectors.toList());
        //1.查询出顶层父类信息
        List<CategoryEntity> oList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
        //2.查询所有除了顶层父类0的信息
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().ne("parent_cid", 0));
        for (CategoryEntity category:oList) {
            //调用递归遍历出所有的子节点
            List<CategoryEntity> list=getChild(category.getCatId(),entities);
            //将这些子节点存入Children中
            category.setChildren(list);
        }
        return oList;
    }

    @Override
    public void removeMounByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否别其它节点引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override//2.25.255//255通过最底层id获得分类的全路径
    public Long[] getAtterPath(Long catelogId) {
        List<Long> list = new ArrayList();
        list = getPathTree(catelogId,list);
        Collections.reverse(list);
        return list.toArray(new Long[list.size()]);
    }

    /**
     * @CacheEvict缓存删除
     * @Caching操作多种
     * @param category
     */
//    @CacheEvict(value = "category",key = "'getLevelOne'")
    //操作多种
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevelOne'"),
//            @CacheEvict(value = "category",key = "'getCatLogJson'")
//    }
//    )
    //删除多个缓存
    @CacheEvict(value = "category",allEntries = true)
    @Override
    public void updateDetail(CategoryEntity category) {
        String name = category.getName();
        Long catId = category.getCatId();
        baseMapper.updateById(category);
        if (StringUtils.isNotBlank(name)){
            categoryBrandRelationService.updateCategery(catId,name);
        }
    }

    @Cacheable(value = "category",key = "#root.methodName")//开启缓存注解
    @Override
    public List<CategoryEntity> getLevelOne() {
        long l = System.currentTimeMillis();
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("查询数据库");
//        System.out.println("消耗的时间："+ (System.currentTimeMillis() - l));
        return entities;
    }

    //缓存数据
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    @Override
    public Map<String, List<CateLog2Vo>> getCatLogJson() {
        System.out.println("查询了数据库");
        //优化循环查询数据库 查询出所有的的数据
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //查询出所有一级分类
        List<CategoryEntity> levelOne = getParentCid(entityList, 0L);
        //封装数据
        Map<String, List<CateLog2Vo>> longListMap = levelOne.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //获取1级分类的所有父id
            Long catId1 = v.getCatId();
            //查询二级分类
            List<CategoryEntity> entities = getParentCid(entityList, catId1);
            List<CateLog2Vo> collect = null;
            if (entities != null) {
                collect = entities.stream().map(l2 -> {
                    //获取二级分类的id
                    Long catId2 = l2.getCatId();
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(catId1.toString(), null, catId2.toString(), l2.getName());
                    //查询三级分类
                    List<CategoryEntity> entities1 = getParentCid(entityList, catId2);
                    if (entities1 != null) {
                        List<CateLog2Vo.CateLog3Vo> collect3 = entities1.stream().map(l3 -> {
                            //获取三级分类的id
                            Long catId3 = l3.getCatId();
                            CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo(catId2.toString(), catId3.toString(), l3.getName());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(collect3);
                    }


                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return longListMap;
    }

    public Map<String, List<CateLog2Vo>> getCatLogJson2(){
        //使用redis缓存数据
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catLogJson = ops.get("catLogJson");
        if (StringUtils.isEmpty(catLogJson)){
            //缓存中查询数据，如果没有，查询数据库，放入缓存
            System.out.println("缓存没有，查询数据库");
            Map<String, List<CateLog2Vo>> cateLogJson = getCateLogFromRedissonJson();
            //序列化转换为json对象
            String s = JSON.toJSONString(cateLogJson);
            ops.set("catLogJson",s,1, TimeUnit.DAYS);
            return cateLogJson;
        }
        System.out.println("缓存命中直接返回");
        Map<String, List<CateLog2Vo>> longListMap = JSON.parseObject(catLogJson, new TypeReference<Map<String, List<CateLog2Vo>>>() {});
        return longListMap;
    }

    /**
     * 缓存一致性
     * 使用redisson
     * @return
     */
    public Map<String, List<CateLog2Vo>> getCateLogFromRedissonJson() {
        //设置UUID为lock锁的value值，保证删除的是自己的锁
        RLock lock = redisson.getLock("Lock");
        //加锁成功
        lock.lock();
        System.out.println("获取分布式锁成功");
        Map<String, List<CateLog2Vo>> redisDataFromDB;
        try {
            redisDataFromDB = getRedisDataFromDB();
        }finally {
            lock.unlock();
        }
        return redisDataFromDB;

    }

    //使用分布式锁
    public Map<String, List<CateLog2Vo>> getCateLogFromRedisJson() {
        //设置UUID为lock锁的value值，保证删除的是自己的锁
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //添加锁，并为锁添加过期时间，保证这个是原子性操作
        Boolean lock = ops.setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);

        if (lock){
            //加锁成功
            System.out.println("获取分布式锁成功");
            Map<String, List<CateLog2Vo>> redisDataFromDB;
            String lockValue = ops.get("lock");
            try {
                redisDataFromDB = getRedisDataFromDB();
            }finally {
                String script  = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\nthen\n    return redis.call(\"del\",KEYS[1])\nelse\n    return 0\nend";
                //删除锁
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class), Arrays.asList("lock"), lockValue);
            }
            return redisDataFromDB;
        }else {
            //占锁失败，休眠会继续占锁
            try {
                System.out.println("占锁失败等待重试");
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //休眠0.1s后，重新调用，自旋
            return getCateLogFromRedisJson();
        }

    }

    private Map<String, List<CateLog2Vo>> getRedisDataFromDB() {
        String catLogJson = stringRedisTemplate.opsForValue().get("catLogJson");
        if (StringUtils.isNotEmpty(catLogJson)) {
            Map<String, List<CateLog2Vo>> longListMap = JSON.parseObject(catLogJson, new TypeReference<Map<String, List<CateLog2Vo>>>() {
            });
            return longListMap;
        }
        System.out.println("查询了数据库");
        //优化循环查询数据库 查询出所有的的数据
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //查询出所有一级分类
        List<CategoryEntity> levelOne = getParentCid(entityList, 0L);
        //封装数据
        Map<String, List<CateLog2Vo>> longListMap = levelOne.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //获取1级分类的所有父id
            Long catId1 = v.getCatId();
            //查询二级分类
            List<CategoryEntity> entities = getParentCid(entityList, catId1);
            List<CateLog2Vo> collect = null;
            if (entities != null) {
                collect = entities.stream().map(l2 -> {
                    //获取二级分类的id
                    Long catId2 = l2.getCatId();
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(catId1.toString(), null, catId2.toString(), l2.getName());
                    //查询三级分类
                    List<CategoryEntity> entities1 = getParentCid(entityList, catId2);
                    if (entities1 != null) {
                        List<CateLog2Vo.CateLog3Vo> collect3 = entities1.stream().map(l3 -> {
                            //获取三级分类的id
                            Long catId3 = l3.getCatId();
                            CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo(catId2.toString(), catId3.toString(), l3.getName());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(collect3);
                    }


                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        String s = JSON.toJSONString(catLogJson);
        stringRedisTemplate.opsForValue().set("catLogJson", s, 1, TimeUnit.DAYS);
        return longListMap;
    }

    @Override
    public Map<String, List<CateLog2Vo>> getCateLogJson() {
        synchronized (this){
            return getRedisDataFromDB();
        }

    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> entityList,Long catId) {
        List<CategoryEntity> collect = entityList.stream().filter(item -> item.getParentCid().equals(catId)).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", catId1));
    }

    public List<Long> getPathTree(Long catelogId, List<Long> list){
        list.add(catelogId);
        CategoryEntity category = baseMapper.selectById(catelogId);
        if(category.getParentCid() != 0){
            getPathTree(category.getParentCid(),list);
        }
        return list;
    }

    private List<CategoryEntity> getChild(Long catId, List<CategoryEntity> oList) {
        List<CategoryEntity> arrays = new ArrayList<>();
        for (CategoryEntity category:oList) {
            //当前的id
            Long id = category.getCatId();
            //当前的父id
            Long parentCid = category.getParentCid();
            //long类型转换为String类型
            String s = parentCid.toString();
            if(StringUtils.isNotBlank(s)) {
                //采用递归遍历
                if (parentCid.equals(catId)) {
                    List<CategoryEntity> child = getChild(id, oList);
                    //查询出对应的父id存放到Children中
                    category.setChildren(child);
                    //添加到ArraysList集合中
                    arrays.add(category);
                }
            }
        }
        return arrays;
    }

}